import axios from 'axios'
// import Qs from 'qs'
import router from '@/router/index'
import { getToken } from '../utils/user'

const toLogin = () => {
  router.push({
    path: '/',
    query: {
      redirect: router.currentRoute.fullPath
    }
  })
}

const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000,
  responseType: 'json',
  withCredentials: true
})

api.interceptors.request.use(
  request => {
    const token = getToken() || ''

    request.headers = {
      'content-Type': 'application/json;charset=utf-8',
      token: token
    }
    return request
  }
)

api.interceptors.response.use(
  response => {
    const data = response.data
    if (data.code == 401) {
      localStorage.removeItem('token')
      toLogin()
    }

    return Promise.resolve(response.data)
  },
  error => {
    return Promise.reject(error)
  }
)

export default api
